﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.ProjectFrom
{
    /// <summary>
    /// 项目表单列表窗体
    /// </summary>
    public partial class ProjectFromForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectFromForm()
        {
            InitializeComponent();
        }
        private int pageIndex = 1; // 当前页码
        private int pageSize = 3; // 每页显示的记录数
        private int totalCount = 0; // 总记录数
        private int totalPages = 0;// 总页数

        /// <summary>
        /// 加载项目表单数据
        /// </summary>
        /// <returns></returns>
        private async Task ReInit(string projectName="")
        {
            List<ProjectFromOutput> projectFromOutputs = new List<ProjectFromOutput>();

            if (string.IsNullOrEmpty(projectName))
            {
                projectFromOutputs = await GetProjectFromList();
            }
            else
            {
                projectFromOutputs = await GetProjectFromQueryList(projectName);
            }

            // 将查询结果直接设置为数据源
            gridControl1.DataSource = projectFromOutputs;


            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;

            if (gridView != null)
            {
                gridView.Columns.Clear();

                gridView.Columns.AddVisible("Id", "项目表单编号");
                gridView.Columns.AddVisible("ProjectName", "项目表单名称");
                gridView.Columns.AddVisible("ProjectType", "项目表单类型");
                // 添加项目维护名称列 - 这是关键修改
                gridView.Columns.AddVisible("ProjectMaintenanceNames", "检验项目");

                // 设置项目维护名称列的宽度和格式
                var maintenanceNamesColumn = gridView.Columns["ProjectMaintenanceNames"];

                gridView.Columns.AddVisible("ProjectDescription", "项目表单描述");
                gridView.Columns.AddVisible("CreatedBy", "创建人");
                // 为日期时间列设置格式
                var createdTimeColumn = gridView.Columns.AddVisible("CreatedTime", "创建时间");
                gridView.Columns.AddVisible("UpdatedBy", "更新人");
                var updatedTimeColumn = gridView.Columns.AddVisible("UpdatedTime", "更新时间");
                // 设置日期时间格式为 yyyy-MM-dd HH:mm:ss
                createdTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                createdTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";

                updatedTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                updatedTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            }
            // 如果还没有“操作”列，则添加操作列（包含删除和编辑按钮）
            if (gridView.Columns["操作"] == null)
            {
                // 添加“操作”列
                var col = gridView.Columns.AddVisible("操作", "操作");

                // 设置为非绑定列（自定义按钮）
                col.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                // 始终显示按钮
                col.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways;

                // 创建按钮编辑器
                RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
                buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor; // 隐藏文本框，仅显示按钮
                buttonEdit.Buttons.Clear();
                // 添加“删除”按钮
                buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph)
                {
                    Caption = "删除",
                    Kind = ButtonPredefines.Glyph,
                    // 可选：设置按钮图片为 null，仅显示文字
                    ImageOptions = { Image = null } // 不显示图片
                });
                // 添加“编辑”按钮
                buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph)
                {
                    Caption = "编辑",
                    Kind = ButtonPredefines.Glyph,
                    // 可选：设置按钮图片为 null，仅显示文字
                    ImageOptions = { Image = null } // 不显示图片
                });
                // 按钮点击事件处理
                buttonEdit.ButtonClick += async (s, a) =>
                {
                    // 获取当前选中的行
                    var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                    var rowHandle = view.FocusedRowHandle;
                    var row = view.GetRow(rowHandle) as ProjectFromOutput;
                    if (row != null)
                    {
                        if (a.Button.Index == 0)// 删除按钮
                        {
                            Console.WriteLine($"删除按钮被点击，ID: {row.Id}"); // 调试信息
                            long id = row.Id;
                            // 调用删除方法
                            await DeletedProjectFrom(id);
                        }
                        else if (a.Button.Index == 1)// 编辑按钮
                        {
                            // 弹出编辑窗口，回显数据并支持修改
                            using (var client = new HttpClient())
                            {
                                // 获取当前设备台账详细信息
                                var response = client.GetStringAsync($"http://47.110.243.157:5229/api/ProjectForm/GetProjectFormValue?id={row.Id}").Result;
                                var ProjectFrom = JsonConvert.DeserializeObject<ApiResult<ProjectFromOutput>>(response);
                                ProjectFrom.Data.Id = row.Id;
                                ProjectFromEditForm projectFromEditForm = new ProjectFromEditForm(); // 实例化编辑窗体

                                // 回显数据
                                projectFromEditForm.GetProjectFromData(ProjectFrom.Data);
                                // 显示编辑窗口
                                var result = projectFromEditForm.ShowDialog();
                                if (result == DialogResult.OK)
                                {
                                    // 编辑成功后，刷新设备台账列表
                                    await ReInit();
                                }
                            }
                        }
                    }
                };
                // 将按钮编辑器赋给“操作”列
                col.ColumnEdit = buttonEdit;
            }
        }

        /// <summary>
        /// 查询项目表单数据
        /// </summary>
        /// <param name="projectName"></param>
        public async Task<List<ProjectFromOutput>> GetProjectFromQueryList(string projectName)
        {
            try
            {
                using (var clien = new HttpClient())
                {
                    // 构造查询参数字符串，包含分页参数
                    string queryParams = $"PageIndex={pageIndex}&PageSize={pageSize}";
                    // 如果有条件，则添加条件查询参数

                    if (!string.IsNullOrEmpty(projectName))
                    {
                        queryParams += $"&ProjectName={projectName}";
                    }

                    
                    var response = await clien.GetStringAsync($"http://47.110.243.157:5229/api/ProjectForm/GetProjectFormList?{queryParams}");
                    return JsonConvert.DeserializeObject<ApiPaging<ProjectFromOutput>>(response).PageData;

                }
            }
            catch (Exception ex)
            {
                // 查询过程中发生异常，弹窗提示错误信息，并返回空列表
                MessageBox.Show($"查询出错：{ex.Message}");
                return new List<ProjectFromOutput>();
            }
        }

        /// <summary>
        /// 获取项目表单数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ProjectFromForm_Load(object sender, EventArgs e)
        {
            await ReInit();
        }

        /// <summary>
        /// 获取项目表单数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProjectFromOutput>> GetProjectFromList()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync($"http://47.110.243.157:5229/api/ProjectForm/GetProjectFormList?PageIndex={pageIndex}&PageSize={pageSize}");
                var result = JsonConvert.DeserializeObject<ApiPaging<ProjectFromOutput>>(response);
                totalCount = result.TotalCount;
                totalPages = (int)Math.Ceiling((totalCount * 1.0) / pageSize);
                return result.PageData;
            }
        }

        /// <summary>
        /// 添加项目表单按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddProjectFromButton1_Click(object sender, EventArgs e)
        {
            ProjectFromAddForm projectFromAddForm = new ProjectFromAddForm();
            projectFromAddForm.ShowDialog();
            if(projectFromAddForm.DialogResult == DialogResult.OK)
            {
                ProjectFromForm_Load(sender, e);
            }
        }

        /// <summary>
        /// 删除项目表单按钮点击事件
        /// </summary>
        /// <param name="id"></param>
        private async Task DeletedProjectFrom(long id)
        {
            try
            {
                // 添加确认对话框
                DialogResult result = XtraMessageBox.Show("确定要删除此项目表单记录吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes)
                    return;
                using (var client = new HttpClient())
                {
                    var response = await client.DeleteAsync($"http://47.110.243.157:5229/api/ProjectForm/DeleteProjectForm?id={id}");

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        await ReInit(); // 刷新数据
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"删除失败！状态码：{response.StatusCode}，错误信息：{errorContent}",
                            "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除操作出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 查询点击按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void QueryButton2_Click(object sender, EventArgs e)
        {
            // 获取查询条件
            string projectName = ProjectName.Text.Trim();
            await ReInit(projectName);

            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                //提示查询到的数量
                var totalCount = gridView.DataRowCount;
                XtraMessageBox.Show($"查询到{totalCount}条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ResetButton3_Click(object sender, EventArgs e)
        {
            ProjectName.Text = "";
            await ReInit();
        }

        /// <summary>
        /// 上一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PrevPageButton5_Click(object sender, EventArgs e)
        {
            if (pageIndex <= 1) 
            {
                    XtraMessageBox.Show("已经是第一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
            }
            pageIndex -= 1;
            await ReInit();
        }
        /// <summary>
        /// 下一页按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void NextPageButton4_Click(object sender, EventArgs e)
        {
            if (pageIndex >=totalPages)
            {
                XtraMessageBox.Show("已经是最后一页了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            pageIndex += 1;
            await ReInit();
        }
    }
}